﻿using Microsoft.AspNetCore.Mvc;
using Qzb.MicroService.Common.ConsulExtensions.Client;
using Qzb.MicroService.Common.HttpClientExtensions;
using Qzb.MicroService.Interface;
using Qzb.MicroService.Model;

namespace Qzb.MicroService.Client.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ConsulDemoController : ControllerBase
    {
        private readonly IUserService _userService;

        private readonly IHttpRequest _httpRequest;

        private readonly ConsulDispatcher _consulDispatcher;

        public ConsulDemoController(IUserService userService, IHttpRequest httpRequest, ConsulDispatcher consulDispatcher)
        {
            _userService = userService;
            _httpRequest = httpRequest;
            _consulDispatcher = consulDispatcher;
        }

        [HttpGet()]
        [Route("Test")]
        public IEnumerable<User> 代码直接调用()
        {
            return _userService.GetUsers();
        }

        [HttpGet()]
        [Route("WebApiTest")]
        public IEnumerable<User>? 单个分布式调用()
        {
            return _httpRequest.Get<IEnumerable<User>>("http://localhost:5077/api/User/List");
        }

        [HttpGet()]
        [Route("NginxTest")]
        public IEnumerable<User>? Nginx调用()
        {
            return _httpRequest.Get<IEnumerable<User>>("http://localhost:8080/api/User/List");
        }

        [HttpGet()]
        [Route("ConsulTest")]
        public IEnumerable<User>? Consul调用()
        {
            // dotnet run --urls=http://localhost:5077 --ConsulRegisterOptions:ServicePort=5077 --ConsulRegisterOptions:Tag:1
            // dotnet run --urls=http://localhost:5078 --ConsulRegisterOptions:ServicePort=5078 --ConsulRegisterOptions:Tag:5
            // dotnet run --urls=http://localhost:5079 --ConsulRegisterOptions:ServicePort=5079 --ConsulRegisterOptions:Tag:10

            // dotnet run --urls=http://localhost:5074

            var url = _consulDispatcher.MapAddress("MicroServiceApi", "/api/User/List");
            if (string.IsNullOrEmpty(url))
            {
                Console.WriteLine("无服务");
                return null;
            }

            return _httpRequest.Get<IEnumerable<User>>(url);
        }
    }
}
